package com.caiheng.api.util;

import org.apache.commons.math3.stat.descriptive.moment.Mean;

/**
 * @创建者：zhouwei
 * @创建时间：2022/5/9
 * @描述：
 */
public class RegressionEquation {
    //需要预测的变量
    private double[] dependentValues;

    //用来预测因变量值的一个或多个变量
    private double[] independentValues;

    public RegressionEquation(double[] dependentValues, double[] independentValues) {
        this.dependentValues = dependentValues;
        this.independentValues = independentValues;
    }

    public double getMean(double[] dd) {
        Mean meanUtil = new Mean();
        return meanUtil.evaluate(dd);
    }

    /**
     *  只包含一个自变量和一个因变量的回归分析。简单线性回归方程的图形是一条直线，b0值代表y轴的截距，b1值代表斜率。
     * @return
     */
    public double[] getRegressionModel() {
        if(dependentValues.length!=independentValues.length) {
            return null;
        }
        Mean meanUtil = new Mean();
        double xmean = meanUtil.evaluate(independentValues);
        double ymean = meanUtil.evaluate(dependentValues);
        double numerator = 0d;
        double denominator = 0d;
        for(int i = 0; i < dependentValues.length;i++) {
            double x = independentValues[i];
            double y = dependentValues[i];
            numerator = numerator + (x - xmean) * (y - ymean);
            denominator = denominator + (x - xmean) * (x - xmean);
        }
        double b1 = numerator / denominator;
        double b0 = ymean - b1 * xmean;
        double[] model= {b0, b1};
        return model;
    }
}
